package com.ai.sb.service.impl;

import com.ai.sb.dao.SbPrizeMapper;
import com.ai.sb.dao.SbPrizeRecordMapper;
import com.ai.sb.dao.SbSettingMapper;
import com.ai.sb.dao.SbUserMapper;
import com.ai.sb.dto.PrizeDto;
import com.ai.sb.model.*;
import com.ai.sb.service.SbPrizeService;
import com.ai.sb.core.AbstractService;
import com.ai.sb.util.BaseUtil;
import com.ai.sb.util.MobileUtil;
import com.ai.sb.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


/**
 * Created by CodeGenerator on 2018/06/09.
 */
@Service
@Transactional
public class SbPrizeServiceImpl extends AbstractService<SbPrize> implements SbPrizeService {
    private Logger logger = LoggerFactory.getLogger(SbPrizeServiceImpl.class);
    @Resource
    private SbPrizeMapper sbPrizeMapper;
    @Resource
    private SbPrizeRecordMapper sbPrizeRecordMapper;
    @Resource
    private SbUserMapper sbUserMapper;
    @Resource
    private SbSettingMapper sbSettingMapper;
    @Value("${my-moblie.mobileFolwUrl}")
    private String mobileFolwUrl;
    @Value("${my-moblie.mobileFolwStaffId}")
    private String mobileFolwStaffId;
    @Value("${my-moblie.mobileCode}")
    private String mobileCode;


    @Override
    public Result receivePrize(String userId,String recordType) {
        logger.info("领奖，参数userID：{}",userId);
        Random random = new Random();
        int s = random.nextInt(100);
        logger.info("随机奖券种类概率值：{}",s);
        Date now = new Date();
        SbPrizeRecord sbPrizeRecord = new SbPrizeRecord();
        SbPrize prize = null;
        boolean isUk = false;
        SbUser sbUser = sbUserMapper.selectByPrimaryKey(userId);
        if(recordType.equals("wx")){
            if(sbUser.getSbWxCount()<1){
                return Result.fail("碎冰次数已用完");
            }else{
                sbUser.setSbWxCount(sbUser.getSbWxCount()-1);
            }
        }else if(recordType.equals("app")){
            if(sbUser.getSbAppCount()<1){
                return Result.fail("碎冰次数已用完");
            }else{
                sbUser.setSbAppCount(sbUser.getSbAppCount()-1);
            }
        }
        SbSetting sbOddsS = sbSettingMapper.selectByPrimaryKey("sb_odds_s");
        int sbOddss = random.nextInt(sbOddsS.getSetValue());
        SbSetting sbOddsY = sbSettingMapper.selectByPrimaryKey("sb_odds_y");
        if(sbOddss > sbOddsY.getSetValue()){
            logger.info("修改用户碎冰数量：",sbUser);
            int z = sbUserMapper.updateByPrimaryKeySelective(sbUser);
            logger.info("碎冰数量修改结果：{}",z);
            return Result.fail("大奖与您擦肩而过");
        }
        //判断异业还是流量
        SbSetting yyOddds = sbSettingMapper.selectByPrimaryKey("ye_odds");
        if(s<yyOddds.getSetValue()){
            isUk = true;
            logger.info("异业卷分支");
            List<SbPrize> prizes = sbPrizeMapper.selByPrizeType("1");
            s = random.nextInt(100);
            logger.info("异业劵概率值：{}",s);
            if(s<prizes.get(0).getPrizeOdds()){
                prize = prizes.get(0);
            }else if(s<prizes.get(1).getPrizeOdds()+prizes.get(0).getPrizeOdds()){
                prize = prizes.get(1);
            }else{
                prize = prizes.get(2);
            }
        }else{
            isUk = false;
            logger.info("流量劵分支");
            List<SbPrize> prizes = sbPrizeMapper.selByPrizeType("2");
            s = random.nextInt(100);
            logger.info("流量劵概率值：{}",s);
            if(s<prizes.get(0).getPrizeOdds()){
                prize = prizes.get(0);
            }else if(s<prizes.get(1).getPrizeOdds()+prizes.get(0).getPrizeOdds()){
                prize = prizes.get(1);
            }else if(s<prizes.get(2).getPrizeOdds()+prizes.get(1).getPrizeOdds()+prizes.get(0).getPrizeOdds()){
                prize = prizes.get(2);
            }else{
                prize = prizes.get(3);
            }

        }
        logger.info("奖品：{}",prize);
        sbPrizeRecord.setId(BaseUtil.getUUID());
        sbPrizeRecord.setUserId(userId);
        sbPrizeRecord.setPrizeId(prize.getId());
        if(prize.getPrizeCount() < 1){
            logger.info("奖品已领取完");
            logger.info("修改用户碎冰数量：",sbUser);
            int z = sbUserMapper.updateByPrimaryKeySelective(sbUser);
            logger.info("碎冰数量修改结果：{}",z);
            return Result.fail("大奖与您擦肩而过");
        }
        if(isUk){
            SbPrizeRecord qs = new SbPrizeRecord();
            qs.setpUk(userId+prize.getId());
            SbPrizeRecord rs = sbPrizeRecordMapper.selectOne(qs);
            if(rs!=null){
                logger.info("已领取过奖品");
                logger.info("修改用户碎冰数量：",sbUser);
                int z = sbUserMapper.updateByPrimaryKeySelective(sbUser);
                logger.info("碎冰数量修改结果：{}",z);
                return Result.fail("大奖与您擦肩而过");
            }
            sbPrizeRecord.setpUk(userId+prize.getId());
        }else{
            //用户添加流量
            String str = prize.getPrizeName();
            int f = Integer.parseInt(str.replace("M",""));
            logger.info("用户添加流量：",f);
            sbUser.setFlow(sbUser.getFlow()+f);
        }
        logger.info("修改用户碎冰数量：",sbUser);
        int z = sbUserMapper.updateByPrimaryKeySelective(sbUser);
        logger.info("碎冰数量修改结果：{}",z);
        sbPrizeRecord.setReceiveTime(now);
        logger.info("修改奖品数量");
        prize.setPrizeCount(prize.getPrizeCount()-1);
        int j = sbPrizeMapper.updateByPrimaryKeySelective(prize);
        logger.info("奖品数量修改结果：{}",j);
        logger.info("插入奖品记录：{}",sbPrizeRecord);
        int i = sbPrizeRecordMapper.insertSelective(sbPrizeRecord);
        logger.info("插入结果：{}",i);
        return Result.success(prize);
    }

    @Override
    public Result receiveFlow(PrizeDto prizeDto) {
        logger.info("领取流量，参数：{}",prizeDto);
        SbPrize sbPrize = sbPrizeMapper.selectByPrimaryKey(prizeDto.getPrizeId());
//        SbPrizeRecord qs = new SbPrizeRecord();
//        qs.setpUk(prizeDto.getUserId()+prizeDto.getPrizeId());
//        SbPrizeRecord rs = sbPrizeRecordMapper.selectOne(qs);
        //查询流量劵是否够领取流量
        SbUser sbUser = sbUserMapper.selectByPrimaryKey(prizeDto.getUserId());
        if(sbPrize.getPrizeOdds()>sbUser.getFlow()){
            return Result.fail("用户流量券不足");
        }
        if(sbPrize.getPrizeCount()<1){
            return Result.fail("奖品已被抢光");
        }
        logger.info("查询是否已经领取");
        if("3".equals(sbPrize.getPrizeType())){
            SbPrize qq = new SbPrize();
            qq.setPrizeType(sbPrize.getPrizeType());
            List<SbPrize> prizes = sbPrizeMapper.select(qq);
            for (SbPrize prize : prizes) {
                SbPrizeRecord qs = new SbPrizeRecord();
                qs.setpUk(prizeDto.getUserId()+prize.getId());
                SbPrizeRecord rs = sbPrizeRecordMapper.selectOne(qs);
                if(rs!=null)return Result.fail("已领取过流量");
            }
        }
        String offerId = null;
        switch (sbPrize.getPrizeOdds()){
            case 50:
                offerId = "22CAZ1011398";
                break;
            case 100:
                offerId = "22CAZ03665";
                break;
            case 200:
                offerId = "22CAZ04058";
                break;
            case 500:
                offerId = "22CAZ1014044";
                break;
            case 1024:
                offerId = "22CAZ1014045";
                break;
                default:
                    break;
        }
        boolean isFlow;
        if(offerId!=null){
            MobileUtil mobileUtil = new MobileUtil(sbUser.getTelNum(),offerId,mobileFolwUrl,mobileFolwStaffId,mobileCode);
            isFlow = mobileUtil.toFlow();
            if(!isFlow){
                logger.info("远程调用下发流量失败");
                return Result.fail("系统内部错误");
            }
        }else{
            logger.info("没有指定流量值");
            return Result.fail("系统内部错误");
        }
        SbPrizeRecord sbPrizeRecord = new SbPrizeRecord();
        sbPrizeRecord.setId(BaseUtil.getUUID());
        sbPrizeRecord.setUserId(prizeDto.getUserId());
        sbPrizeRecord.setPrizeId(prizeDto.getPrizeId());
        sbPrizeRecord.setpUk(prizeDto.getUserId()+prizeDto.getPrizeId());
        sbPrizeRecord.setReceiveTime(new Date());
        logger.info("修改流量奖品数量");
        sbPrize.setPrizeCount(sbPrize.getPrizeCount()-1);
        int z = sbPrizeMapper.updateByPrimaryKeySelective(sbPrize);
        logger.info("流量奖品数量修改结果:{}",z);
        logger.info("修改用户流量为：{}",sbUser.getFlow()-sbPrize.getPrizeOdds());
        sbUser.setFlow(sbUser.getFlow()-sbPrize.getPrizeOdds());
        int j = sbUserMapper.updateByPrimaryKeySelective(sbUser);
        logger.info("用户流量修改结果：{}",j);
        logger.info("插入流量领取记录：{}",sbPrizeRecord);
        int i = sbPrizeRecordMapper.insertSelective(sbPrizeRecord);
        logger.info("插入记录：{}",i);
        return Result.success(sbPrize.getPrizeValue());
    }

    @Override
    public Result selFlow(String userId) {
        logger.info("查询可兑换的流量，userID:{}",userId);
        //根据用户Id查询用户
        SbUser sbUser = sbUserMapper.selectByPrimaryKey(userId);
        List<SbPrize> sbPrizes = sbPrizeMapper.selByPrizeType("3");
        boolean b = false;
        for (SbPrize sbPrize : sbPrizes) {
            SbPrizeRecord qs = new SbPrizeRecord();
            qs.setpUk(userId+sbPrize.getId());
            SbPrizeRecord rs = sbPrizeRecordMapper.selectOne(qs);
            if(rs!=null)b = true;
        }
        //是否兑换过
        if(b){
            for (SbPrize sbPrize : sbPrizes) {
                SbPrizeRecord qs = new SbPrizeRecord();
                qs.setpUk(userId + sbPrize.getId());
                SbPrizeRecord rs = sbPrizeRecordMapper.selectOne(qs);
                if (rs != null) {
                    sbPrize.setHas(true);
                    sbPrize.setEnable(false);
                }else{
                    sbPrize.setHas(false);
                    sbPrize.setEnable(false);
                }
            }
        }else{
            for (SbPrize sbPrize : sbPrizes) {
                if(sbPrize.getPrizeCount()<=0){
                    sbPrize.setEnable(false);
                    continue;
                }//数量判断
                //判断用户流量是否够
                if(sbUser.getFlow()==null){
                    sbPrize.setEnable(false);
                }else{
                    if(sbUser.getFlow() >= sbPrize.getPrizeOdds()){
                        sbPrize.setEnable(true);
                    }else{
                        sbPrize.setEnable(false);
                    }
                }
            }
        }
        logger.info("兑换流量查询结果：{}",sbPrizes);
        return Result.success(sbPrizes);
    }

    @Override
    public Result selMyPrize(String userId) {
        List<SbPrize> rsList = new ArrayList<>();
        List<SbPrizeRecord> sbPrizeRecords = sbPrizeRecordMapper.selByUserId(userId);
        for (SbPrizeRecord sbPrizeRecord : sbPrizeRecords) {
            SbPrize sbPrize = sbPrizeMapper.selectByPrimaryKey(sbPrizeRecord.getPrizeId());
            if(!sbPrize.getPrizeType().equals("2")){
                sbPrize.setPrizeTime(sbPrizeRecord.getReceiveTime());
                rsList.add(sbPrize);
            }
        }
        return Result.success(rsList);
    }

    @Override
    public Result bb() {
        List<SbPrizeRecord> sbPrizeRecords = sbPrizeRecordMapper.selectAll();
        boolean isAllOk = true;
        for (SbPrizeRecord sbPrizeRecord : sbPrizeRecords) {
            if(sbPrizeRecord.getpUk()!=null){
                SbPrize sbPrize = sbPrizeMapper.selectByPrimaryKey(sbPrizeRecord.getPrizeId());
                SbUser sbUser = sbUserMapper.selectByPrimaryKey(sbPrizeRecord.getUserId());
                //批量兑换的时间
                long tt = sbPrizeRecord.getReceiveTime().getTime();
                DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
                Date myDate1 = null;
                try {
                    myDate1 = dateFormat1.parse("2018-06-28");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                System.out.println(myDate1);
                long end = myDate1.getTime();

                String offerId = null;
                switch (sbPrize.getPrizeOdds()){
                    case 50:
                        offerId = "22CAZ1011398";
                        break;
                    case 100:
                        offerId = "22CAZ03665";
                        break;
                    case 200:
                        offerId = "22CAZ04058";
                        break;
                    case 500:
                        offerId = "22CAZ1014044";
                        break;
                    case 1024:
                        offerId = "22CAZ1014045";
                        break;
                    default:
                        break;
                }
                boolean isFlow;
                logger.info("补发记录，{}",sbPrizeRecord);
                if(offerId!=null && tt<end){
                    logger.info("补发===》{}====>{}",sbUser.getTelNum(),sbPrize.getPrizeValue());
                    MobileUtil mobileUtil = new MobileUtil(sbUser.getTelNum(),offerId,mobileFolwUrl,mobileFolwStaffId,mobileCode);
                    isFlow = mobileUtil.toFlow();
                    if(!isFlow){
                        logger.info("============="+sbUser.getTelNum()+"远程调用下发流量失败");
                        isAllOk = false;
                    }
                }else{
                    logger.info("============="+sbUser.getTelNum()+"没有指定流量值或非指定时间内的用户");
                    //isAllOk = false;
                }
            }
        }
        return Result.success(isAllOk);
    }
}
